package com.example.hw_3.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.hw_3.common.UserResult;
import com.example.hw_3.common.utils.JwtUtil;
import com.example.hw_3.entity.HwAdminUser;
import com.example.hw_3.service.HwAdminUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

//管理员 CRUD
@RestController
@RequestMapping("/user")
public class HwAdminController {
    @Autowired
    private HwAdminUserService userService;

    // 查询管理员列表，可根据用户名模糊查询
    @GetMapping("/select")
    public UserResult selectUsers(@RequestParam(required = false) String username) {
        QueryWrapper<HwAdminUser> wrapper = new QueryWrapper<>();
        if (username != null && !username.isEmpty()) {
            wrapper.lambda().like(HwAdminUser::getUsername, username);
        }
        List<HwAdminUser> list = userService.list(wrapper);
        return new UserResult(200, "查询成功", list);
    }

    // 登录
    @PostMapping("/login")
    public UserResult login(@RequestBody HwAdminUser user) {
        QueryWrapper<HwAdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        HwAdminUser dbUser = userService.getOne(wrapper);
        if (dbUser != null) {
            // TODO: 生产环境请使用加密密码对比，如 BCryptPasswordEncoder
            if (dbUser.getPassword().equals(user.getPassword())) {
                String token = JwtUtil.generateToken(dbUser.getId().toString());
                Map<String, Object> data = new HashMap<>();
                data.put("token", token);
                data.put("user", dbUser);
                return new UserResult(200, "登录成功", data);
            }
        }
        return new UserResult(401, "用户名或密码错误", null);
    }

    // 注册
    @PostMapping("/register")
    public UserResult register(@RequestBody HwAdminUser user) {
        QueryWrapper<HwAdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", user.getUsername());
        if (userService.count(wrapper) > 0) {
            return new UserResult(400, "用户名已存在", null);
        }
        boolean saved = userService.save(user);
        if (saved) {
            return new UserResult(200, "注册成功", null);
        } else {
            return new UserResult(500, "注册失败", null);
        }
    }
}
